<template>
  <div>
    <el-drawer v-model="dialogVisible" direction="rtl" size="1000">
      <el-container style="width: 100%; height: 100%">
        <el-aside style="width: 380px; height: 100%">
          <el-form ref="ruleFormRef" :rules="rules" :model="addProblemTemplateFormData" style="width: 100%" label-width="122px">
            <el-dialog title="选择服务目录" v-model="dialogServiceDirTableVisible">
              <div :style="{ height: '500px' }">
                <Custemerselect @send-data="sendCompanyNoData" />
              </div>
            </el-dialog>
            <el-dialog v-model="templateNameDialogVisible" title="内容模板名称" width="30%">
              <el-form style="width: 100%" label-width="120px">
                <el-form-item label="知识内容模板名称 :" prop="templateName">
                  <el-input v-model="addProblemTemplateFormData.templateName" />
                </el-form-item>
              </el-form>
              <template #footer>
                <span class="dialog-footer">
                  <el-button type="primary" @click="templateNameBtn(ruleFormRef)">保存</el-button>
                </span>
              </template>
            </el-dialog>
            <div>
              <p>基本信息</p>
            </div>
            <el-form-item class="item" label="标题 :" prop="title" style="width: 98%">
              <el-input v-model="addProblemTemplateFormData.title" />
            </el-form-item>
            <el-form-item class="item" label="知识类型 :" style="width: 98%" prop="categoryName">
              <el-tree-select
                v-model="KnowledgeSelectValue"
                :data="KnowledgeSelectList"
                :render-after-expand="false"
                check-strictly
                check-on-click-node
                @change="changeKnowledge"
              />
            </el-form-item>
            <el-form-item class="item" label="审核状态 :" style="width: 98%">
              <el-checkbox v-model="knowledgeStatusLable" label="1">已审批</el-checkbox>
            </el-form-item>
            <el-form-item class="item" label="关键字 :" style="width: 98%">
              <el-input v-model="addProblemTemplateFormData.keyWords" />
            </el-form-item>
          </el-form>
        </el-aside>
        <el-main style="width: 400px">
          <el-button type="primary" @click="onSubmitFormPre(ruleFormRef)"> 保存 </el-button>
          <el-button type="primary" @click="backList"> 返回列表 </el-button>
          <!-- <el-button type="primary" @click="testbtn"> 测试 </el-button> -->
          <!-- <el-button type="primary" @click="serviceDir"> 服务目录 </el-button> -->
          <div>
            <p>详细信息</p>
          </div>
          <el-tabs v-model="activeName">
            <el-tab-pane label="知识明细" name="zsmx">
              <WangEditor v-model:value="content" height="400px" width="300px" />
            </el-tab-pane>
            <!-- <el-tab-pane label="关联配置项" name="first">
				    <el-button type="primary" @click="selectCiDialogVisible = true"> 添加 </el-button>
				    <el-dialog title="选择关联配置项" v-model="selectCiDialogVisible">
				      <div :style="{ height: '500px' }">
				        <moreSelectCi @send-data="sendCiData" />
				      </div>
				    </el-dialog>
				    <ProTable
				      ref="ciProTable"
				      row-key="id"
				      :indent="20"
				      :data="ciList"
				      :columns="ciColumns"
				      :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
				    >
				
				      <template #operation="scope">
				        <el-button type="primary" link @click="deleteci(scope.$index)">删除</el-button>
				      </template>
				    </ProTable>
				  </el-tab-pane> -->
            <el-tab-pane label="附件" name="second">
              <el-button type="primary" @click="addAttachment"> 添加附件 </el-button>
              <ProTable
                ref="attachmentProTable"
                row-key="id"
                :indent="20"
                :data="attachmentList"
                :columns="attachmentColumns"
                :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
              >
                <!-- 表格操作 -->
                <template #operation="scope">
                  <el-button type="primary" link @click="deleteattachment(scope.$index)">删除</el-button>
                </template>
              </ProTable>
            </el-tab-pane>
            <!-- <el-tab-pane label="关联服务" name="glfw">
					  <el-tree-select
					    style="width: 360px"
					    v-model="serviceDirectorySelectValue"
					    :data="serviceDirectorySelectList"
					    multiple
					    :render-after-expand="false"
					    show-checkbox
					    check-strictly
					    check-on-click-node
					  />
					  <el-button type="primary" @click="addServiceDir"> 添加 </el-button>
					  <ProTable
					    ref="serviceDirectoryProTable"
					    row-key="id"
					    :indent="20"
					    :data="serviceDirectoryList"
					    :columns="serviceDirectoryColumns"
					    :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
					  >
					   
					    <template #operation="scope">
					      <el-button type="primary" link @click="deleteserviceDirectory(scope.$index)">删除</el-button>
					    </template>
					  </ProTable>
				  	</el-tab-pane> -->
          </el-tabs>
        </el-main>
      </el-container>

      <ImportExcel ref="dialogRef" />
    </el-drawer>
  </div>
</template>

<script setup lang="ts" name="basicForm">
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { ref, reactive, onMounted, onBeforeUnmount, defineComponent } from "vue";
import { getjggl, emailtest, emailtestexchange, testSMSAccount, getjgglmessage, mergeCompany } from "@/api/modules/jggl";
import Userselect from "@/views/tools/userSelectbyOrgNo/index.vue";
import { isTelOrFax, isEmail } from "@/utils/eleValidate";
import WangEditor from "@/components/WangEditor/index.vue";
import Custemerselect from "@/views/tools/custemerSelect/index.vue";
import { useRoute, useRouter } from "vue-router";
import { dataDictionaryItemsfindByCode, getCategoryTreeAllData } from "@/api/modules/dataDictionary";
import {
  findPageScheduledTask,
  saveScheduledTask,
  deleteScheduledTask,
  findScheduledTaskById,
  editScheduledTask,
  uploadFile,
  saveRequestTemplate,
  saveProblemTemplate,
  findSubCategorysByEvenId,
  findAttributeList,
  findByTemplateId,
  findCiByIds,
  saveKnowledgeTemplate
} from "@/api/modules/systemTools";
import { useTabsStore } from "@/stores/modules/tabs";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import moreSelectCi from "@/views/tools/moreCiSelect/index.vue";
import ImportExcel from "@/views/tools/uploadFile/index.vue";
import { getCurrentLoginUser } from "@/api/modules/accessController";
import { addKnowledge } from "@/api/modules/knowledge";

const content = ref("");
const router = useRouter();
const route = useRoute();
const tabStore = useTabsStore();
const UserselectRef = ref<InstanceType<typeof Userselect> | null>(null);

const templateNameDialogVisible = ref(false);
const templateNameBtn = async (formEl: FormInstance | undefined) => {
  if (addProblemTemplateFormData.templateName == "") {
    ElMessage({
      type: "error",
      message: "模板名称不能为空"
    });
    return;
  }
  onSubmitForm(formEl);
  templateNameDialogVisible.value = false;
};

const serviceDirectoryProTable = ref<ProTableInstance>();
const serviceDirectoryList = ref<any>([]);

const serviceDirectoryColumns = reactive<ColumnProps<resCIList>[]>([
  { prop: "id", label: "ID", sortable: true },
  { prop: "cname", label: "服务名称", sortable: true, width: 260 },
  { prop: "operation", label: "操作项", fixed: "right", width: 200 }
]);
//关联配置项开始
const ciProTable = ref<ProTableInstance>();
const ciList = ref<any>([]);

const serviceDirectorySelectValue = ref();
const serviceDirectorySelectList = ref<any>([]);

const selectCiDialogVisible = ref(false);
const ciColumns = reactive<ColumnProps<resCIList>[]>([
  { prop: "cino", label: "固定资产编号", sortable: true },
  { prop: "ciname", label: "名称", sortable: true, width: 260 },
  { prop: "categoryName", label: "分类", sortable: true, width: 260 },
  { prop: "status", label: "状态", sortable: true, width: 260 },
  { prop: "operation", label: "操作项", fixed: "right", width: 200 }
]);

// 删除
const deleteci = async (index: any) => {
  ciList.value.splice(index, 1);
};

// 添加关联服务
const addServiceDir = () => {
  serviceDirectorySelectValue.value.forEach(function (element2) {
    traverseTree(serviceDirectorySelectList.value[0], node => {
      if (node.data == element2.toString()) {
        console.log("选中");
        console.log(node);
        let tmp = {
          id: node.attr.id,
          cname: node.attr.cname
        };
        //去重
        let addflag = true;
        serviceDirectoryList.value.forEach(val => {
          if (val.id == tmp.id) {
            addflag = false;
          }
        });
        if (addflag == true) {
          serviceDirectoryList.value.push(tmp);
        } else {
          ElMessage({
            type: "info",
            message: "存在相同数据 :   " + tmp["cname"] + "，  已自动过滤重复数据"
          });
        }
      }
    });
  });
};

//选中资产子组件弹窗回调方法
const sendCiData = (data: [resCIList]) => {
  if (data.length > 0) {
    for (let i = 0; i < data.length; i++) {
      //去重
      let addflag = true;
      ciList.value.forEach(val => {
        if (val.ciId == data[i].ciId) {
          addflag = false;
        }
      });
      if (addflag == true) {
        ciList.value.push(data[i]);
      } else {
        ElMessage({
          type: "info",
          message: "存在相同配置 :   " + data[i]["ciname"] + "，  已自动过滤重复配置"
        });
      }
    }
  }
  selectCiDialogVisible.value = false;
};
export interface resCIList {
  ciname: string;
  cino: string;
  categoryName: string;
  categoryNo: string;
  status: string;
  ciId: number;
  attachmentStr: string;
  fileName: string;
  beginTime: string;
  companyName: string;
  companyNo: number;
  contractName: string;
  contractNo: number;
  dataFlag: number;
  description: string;
  dialect: string;
  endTime: string;
  finishTime: number;
  flagName: string;
  lastUpdater: string;
  packageName: string;
  respondTime: number;
  ruleName: string;
  ruleNo: number;
  rulePackageNo: number;
  salience: number;
  showFinishTime: string;
  showRespondTime: string;
  beforeOrAfter: boolean;
  beforeOrAfterStr: string;
  timeStr: string;
}
//关联配置项结束

//附件开始
const attachmentProTable = ref<ProTableInstance>();
const attachmentList = ref<any>([]);
const attachmentColumns = reactive<ColumnProps<resCIList>[]>([
  { prop: "fileName", label: "文件名称" },
  { prop: "operation", label: "操作项", fixed: "right", width: 200 }
]);
const uploadFileRes = async (param: any) => {
  let res = JSON.parse(JSON.stringify(param));
  let attachmentStr = res.fileName + "==" + res.msg + "==" + res.fileSize + "-s-";
  let attachment = {
    fileName: res.fileName,
    attachmentStr: attachmentStr
  };
  attachmentList.value.push(attachment);
};
// 添加附件
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
const addAttachment = () => {
  const params = {
    title: "",
    tempApi: uploadFile,
    importApi: uploadFile,
    getTableList: ciProTable.value?.getTableList,
    addAttachmentMethod: uploadFileRes
  };
  dialogRef.value?.acceptParams(params);
};
// 删除附件
const deleteattachment = async (index: any) => {
  attachmentList.value.splice(index, 1);
};
//附件结束
const deleteserviceDirectory = async (index: any) => {
  serviceDirectoryList.value.splice(index, 1);
};

//开始
//请求客户
const dialogCompanyNoTableVisible = ref(false);
const dialogCreatedByTableVisible = ref(false); //创建人
const categorySelectValue = ref();
const categorySelectList = ref<any>([]);

//知识类型选择开始
const KnowledgeSelectValue = ref();
const KnowledgeSelectList = ref<any>([]);
const changeKnowledge = (val: any) => {
  traverseTree(KnowledgeSelectList.value[0], node => {
    if (node.value == val.toString()) {
      addProblemTemplateFormData.KnowledgeNo = node.attr.id;
      addProblemTemplateFormData.categoryName = node.attr.cname;
      addProblemTemplateFormData.categoryNo = node.attr.id;
      console.log(node);
    }
  });
};

// 父组件的值
const fatherValue = ref({ orgNo: 1 });
const knowledgeStatusLable = ref(false);
const addProblemTemplateFormData = reactive({
  creator: "",
  companyNo: 1,
  formId: "",
  companyName: "",
  createdByName: "",
  createdByNo: "",
  categoryName: "",
  categoryNo: "",
  attachmentStr: "",
  templateName: "",
  templateId: "",
  templateType: "knowledge",
  title: "",
  keyWords: "",
  knowledgeStatus: 0,
  content: "",
  KnowledgeNo: ""
});

//客户选择子组件弹窗回调方法
const sendCompanyNoData = (data: any) => {
  dialogCompanyNoTableVisible.value = false;
  addProblemTemplateFormData.companyNo = data.orgNo;
  addProblemTemplateFormData.companyName = data.orgName;
  fatherValue.value.orgNo = data.orgNo;
};

// ProTable 实例

const formData = ref({});
const formApi = ref(null);
const formCreateRules = ref<any>([]);
const formCreateRules2 = ref<any>([]);
const option = ref({
  submitBtn: false
});
const dataDictionaryFlagList = ref<any>([]);

const onSubmitFormPre = async (formEl: FormInstance | undefined) => {
  if (content.value == null || content.value == "") {
    ElMessage.error("描述不能为空");
    return;
  }
  templateNameDialogVisible.value = true;
};
const onSubmitForm = async (formEl: FormInstance | undefined) => {
  if (content.value == null || content.value == "") {
    ElMessage.error("描述不能为空");
  }
  addProblemTemplateFormData.knowledgeStatus = knowledgeStatusLable.value == true ? 1 : 0;
  addProblemTemplateFormData.content = content.value.toString();
  let idsStr = "";
  for (let i = 0; i < ciList.value.length; i++) {
    if (idsStr == "") {
      idsStr = "?cinos=" + ciList.value[i].ciId;
    } else {
      idsStr = idsStr + "&cinos=" + ciList.value[i].ciId;
    }
  }
  let serviceDirStr = "";
  for (let i = 0; i < serviceDirectoryList.value.length; i++) {
    if (serviceDirStr == "") {
      serviceDirStr = "problemDTO.serviceDirectoryNos=" + serviceDirectoryList.value[i].id;
    } else {
      serviceDirStr = serviceDirStr + "&problemDTO.serviceDirectoryNos=" + serviceDirectoryList.value[i].id;
    }
  }
  let attachmentStr = "";
  for (let i = 0; i < attachmentList.value.length; i++) {
    if (attachmentStr == "") {
      attachmentStr = attachmentList.value[i].attachmentStr;
    } else {
      attachmentStr += attachmentList.value[i].attachmentStr;
    }
  }
  addProblemTemplateFormData.attachmentStr = attachmentStr;

  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      //校验成功
      //扩展数据saveData
      let saveData = {};
      Object.keys(formData.value).forEach(key => {
        saveData[`${key}`] = `${formData.value[key]}`;
      });
      //识别数据字典名字改为编号
      for (let i = 0; i < dataDictionaryFlagList.value.length; i++) {
        Object.keys(saveData).forEach(key => {
          if ((dataDictionaryFlagList.value[i].id = `${key}`)) {
            (dataDictionaryFlagList.value[i].dataList as any).forEach(function (element) {
              if (element["value"] == `${saveData[key]}`) {
                saveData[`${key}`] = element.dcode;
              }
            });
          }
        });
      }
      saveKnowledgeTemplate(addProblemTemplateFormData, "knowledgeDto", idsStr).then(res => {
        console.log(res);
        ElMessage.success("新增成功");
        tabStore.removeTabs(route.fullPath);
        router.push(`/system/tools/contentTemplateManagement?pageNo=${Math.random().toFixed(3)}`);
      });
      ElMessage.success("保存成功");
    } else {
      ElMessage.error("请正确填写表单");
    }
  });
};

const testbtn = async () => {
  let saveData = {};
  Object.keys(formData.value).forEach(key => {
    saveData[`${key}`] = `${formData.value[key]}`;
  });
  //识别数据字典名字改为编号
  for (let i = 0; i < dataDictionaryFlagList.value.length; i++) {
    Object.keys(saveData).forEach(key => {
      if ((dataDictionaryFlagList.value[i].id = `${key}`)) {
        (dataDictionaryFlagList.value[i].dataList as any).forEach(function (element) {
          if (element["value"] == `${saveData[key]}`) {
            saveData[`${key}`] = element.dcode;
          }
        });
      }
    });
  }
  console.log(saveData);
};
// 返回列表
const dialogVisible = ref(false);
const backList = async () => {
  dialogVisible.value = false;
};
const dialogServiceDirTableVisible = ref(false);
// 服务目录
const serviceDir = async () => {
  dialogServiceDirTableVisible.value = true;
  tabStore.removeTabs(route.fullPath);
  router.push(`/system/tools/regularTaskManagement?pageNo=${Math.random().toFixed(3)}`);
};

//结束

const ruleFormRef = ref<FormInstance>();
const activeName = ref("zsmx");

const rules = reactive<FormRules>({
  companyName: [{ required: true, message: "请选择公司", trigger: "blur" }],
  createdByName: [{ required: true, message: "请选择请求用户", trigger: "blur" }],
  categoryName: [{ required: true, message: "请选择请求分类", trigger: "blur" }],
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  companyNo: [{ required: true, message: "请选择类型", trigger: "blur" }]
});
onMounted(() => {
  //加载公司信息
  getjgglmessage().then(res => {
    let newParams = JSON.parse(JSON.stringify(res));
    addProblemTemplateFormData.companyName = newParams.companyName;
    addProblemTemplateFormData.companyNo = newParams.companyNo == 0 ? 1 : newParams.companyNo;
  });
  //加载用户数据
  getCurrentLoginUser().then(res => {
    let newRes = JSON.parse(JSON.stringify(res));
    addProblemTemplateFormData.createdByNo = newRes.userId;
    addProblemTemplateFormData.createdByName = newRes.fullName;

    addProblemTemplateFormData.creator = newRes.loginName;
  });
  //请求分类选择树
  getCategoryTreeAllData("Problem").then(res => {
    // 使用traverseTree遍历树
    traverseTree(res as any, node => {
      node["lable"] = node.attr.cname;
      node["value"] = node.attr.cname;
    });
    let k: any[] = [];
    k.push(res);
    categorySelectList.value = k;
  });
  //知识类型Knowledge
  getCategoryTreeAllData("Knowledge").then(res => {
    // 使用traverseTree遍历树
    traverseTree(res as any, node => {
      if (node.attr.cname == "知识库分类") {
        node["disabled"] = true;
      }
      node["lable"] = node.attr.cname;
      node["value"] = node.attr.cname;
    });
    let k: any[] = [];
    k.push(res);
    KnowledgeSelectList.value = k;

    // (res as any).forEach(function (element) {
    //   element["lable"] = element["dname"];
    //   element["value"] = element["dname"];
    // });
    // KnowledgeSelectList.value = res as any;
  });
  // //优先级priority
  // dataDictionaryItemsfindByCode("priority").then(res => {
  //   (res as any).forEach(function (element) {
  //     element["lable"] = element["dname"];
  //     element["value"] = element["dname"];
  //   });
  //   prioritySelectList.value = res as any;
  // });
  // //影响effectRange
  // dataDictionaryItemsfindByCode("effectRange").then(res => {
  //   (res as any).forEach(function (element) {
  //     element["lable"] = element["dname"];
  //     element["value"] = element["dname"];
  //   });
  //   effectRangeSelectList.value = res as any;
  // });

  // dataDictionaryItemsfindByCode("seriousness").then(res => {
  //   (res as any).forEach(function (element) {
  //     element["lable"] = element["dname"];
  //     element["value"] = element["dname"];
  //   });
  //   seriousnessSelectList.value = res as any;
  // });

  //服务目录
  getCategoryTreeAllData("Service").then(res => {
    // 使用traverseTree遍历树
    traverseTree(res as any, node => {
      node["lable"] = node.attr.cname;
      node["value"] = node.attr.cname;
    });
    serviceDirectorySelectList.value = [res as any];
  });

  //编辑时加载数据
  let query = JSON.parse(JSON.stringify(route.query));
  // findByTemplateId findCiByIds
  if (query.id != undefined) {
    findByTemplateId({ templateId: query.id }, "templateDTO", []).then(res => {
      let newParams = JSON.parse(JSON.stringify(res));
      // let ciIds=""
      // for(let i=0;i<newParams.dto.relatedCiNos.length;i++){
      //  if(ciIds==""){
      //   ciIds="?ids="+newParams.dto.relatedCiNos[i]
      //  }else{
      //   ciIds+="&ids="+newParams.dto.relatedCiNos[i]
      //  }
      // }
      // findCiByIds(ciIds).then(ciRes=>{
      //  (ciRes as any).forEach(function (element) {
      //   ciList.value.push(element)
      //  });
      // })
      let valArr = newParams.dto.attachmentStr.split("-s-");
      for (let i = 0; i < valArr.length; i++) {
        if (valArr[i] == "") {
          continue;
        }
        let attObj = valArr[i].split("==");
        let attachment = {
          fileName: attObj[0],
          attachmentStr: valArr[i] + "-s-"
        };
        attachmentList.value.push(attachment);
      }
      let serviceNos = newParams.dto.serviceNos == undefined ? {} : newParams.dto.serviceNos;
      Object.keys(serviceNos).forEach(key => {
        let tmpservice = {
          id: `${key}`,
          cname: `${serviceNos[key]}`
        };
        serviceDirectoryList.value.push(tmpservice);
      });

      addProblemTemplateFormData.creator = newParams.dto.creator == undefined ? "" : newParams.dto.creator;
      addProblemTemplateFormData.companyNo = newParams.dto.companyNo == undefined ? "" : newParams.dto.companyNo;
      addProblemTemplateFormData.companyName = newParams.dto.companyName == undefined ? "" : newParams.dto.companyName;
      addProblemTemplateFormData.createdByName = newParams.dto.createdByName == undefined ? "" : newParams.dto.createdByName;
      addProblemTemplateFormData.createdByNo = newParams.dto.createdByNo == undefined ? "" : newParams.dto.createdByNo;
      addProblemTemplateFormData.categoryName = newParams.dto.categoryName == undefined ? "" : newParams.dto.categoryName;
      KnowledgeSelectValue.value = newParams.dto.categoryName == undefined ? "" : newParams.dto.categoryName;
      addProblemTemplateFormData.categoryNo = newParams.dto.categoryNo == undefined ? "" : newParams.dto.categoryNo;
      addProblemTemplateFormData.attachmentStr = newParams.dto.attachmentStr == undefined ? "" : newParams.dto.attachmentStr;

      addProblemTemplateFormData.templateName = newParams.templateName == undefined ? "" : newParams.templateName;
      addProblemTemplateFormData.templateId = newParams.templateId == undefined ? "" : newParams.templateId;
      addProblemTemplateFormData.templateType = newParams.templateType == undefined ? "" : newParams.templateType;
      addProblemTemplateFormData.formId = newParams.formId == undefined ? "" : newParams.formId;

      addProblemTemplateFormData.title = newParams.dto.title == undefined ? "" : newParams.dto.title;
      addProblemTemplateFormData.keyWords = newParams.dto.keyWords == undefined ? "" : newParams.dto.keyWords;
      addProblemTemplateFormData.knowledgeStatus =
        newParams.dto.knowledgeStatus == undefined ? "" : newParams.dto.knowledgeStatus;
      knowledgeStatusLable.value = newParams.dto.knowledgeStatus == "1" ? true : false;
      addProblemTemplateFormData.content = newParams.dto.content == undefined ? "" : newParams.dto.content;
      content.value = newParams.dto.content == undefined ? "" : newParams.dto.content;
    });
  }
});

interface TreeNode {
  value: any;
  lable: any;
  children?: TreeNode[];
  id: string;
  name: string;
  attr: any;
  data: any;
}

function traverseTree(node: TreeNode, callback: (node: TreeNode) => void) {
  callback(node);
  if (node.children) {
    node.children.forEach(child => traverseTree(child, callback));
  }
}
const open = (e: any) => {
  console.log(e);
  dialogVisible.value = true;
};
defineExpose({
  open
});
</script>

<style scoped lang="scss">
@import "./index.scss";
.item {
  width: 500px;
}
</style>
